package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppAdapter;
import com.qiantu.api.entity.ControlDataColorTemperatureBean;

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/09/22
 * desc   : 状态数据列表
 */
public final class ColorTemperatureAdapter extends AppAdapter<ControlDataColorTemperatureBean.ColorData> {

    private int currentSelectedPosition = -1;

    public ColorTemperatureAdapter(@NonNull Context context) {
        super(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private ViewHolder() {
            super(R.layout.item_color_temperature);
        }

        @Override
        public void onBindView(int position) {
            ControlDataColorTemperatureBean.ColorData item = getItem(position);
            TextView textView = (TextView) itemView;
            textView.setText(item.getName());
            if(position == currentSelectedPosition){
                textView.setSelected(true);
            }else{
                textView.setSelected(false);
            }
            Drawable drawable = textView.getCompoundDrawables()[1];
            if (drawable instanceof StateListDrawable) {
                StateListDrawable stateListDrawable = (StateListDrawable) drawable;
                Drawable current = stateListDrawable.getCurrent();
                if (current instanceof LayerDrawable) {
                    LayerDrawable layerDrawable = (LayerDrawable) current;
                    GradientDrawable gradientDrawable = (GradientDrawable) layerDrawable.getDrawable(1);
                    gradientDrawable.setColor(Color.parseColor(item.getColor_16()));
                }
            }
        }
    }

    @Override
    public long getItemId(int position) {
        return getData().get(position).hashCode();
    }

    public void selectItem(int position) {
        currentSelectedPosition = position;
        notifyDataSetChanged();
    }

    public void clearSelected(){
        currentSelectedPosition = -1;
        notifyDataSetChanged();
    }
}